package cn.singlewindow.ha.util.collector.integration.component;

import cn.singlewindow.ha.util.collector.collecter.service.IParserService;
import cn.singlewindow.ha.util.collector.common.util.SpringContextUtils;
import cn.singlewindow.ha.util.collector.integration.util.MessageUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.file.FileHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;

public class HandlerModel implements Runnable {

    private final static Log logger = LogFactory.getLog(HandlerModel.class);

    private Message message;

    public HandlerModel(Message message){
        this.message = message;
    }

    @Override
    public void run() {
        logger.info(message);
//        System.out.println(String.format("HandlerModel [%s]",message));
        MessageHeaders headers = message.getHeaders();
        String filename = (String) headers.get(FileHeaders.FILENAME);

        IParserService iParserService = (IParserService) SpringContextUtils.getBean(IParserService.class);
        if(StringUtils.hasLength(filename)){
            String filenameTemp = filename.toLowerCase();
            boolean parseSuccess = true;
            if(filenameTemp.endsWith(".html")){
                try {
                    parseSuccess = iParserService.htmlParser(new String((byte[]) message.getPayload(),"utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if(filenameTemp.endsWith(".xml")){
            } else if(filenameTemp.endsWith(".xls")||filenameTemp.endsWith(".xlsx")){
            } else {
                parseSuccess = false;
                logger.error(String.format("暂不处理该类型文件,[%s]",filename));
                System.err.println("暂不处理该类型文件"+filename);
            }
            if(parseSuccess){
                logger.info(String.format("处理成功，原始文件已备份,[%s]",filename));
                MessageUtils.backupRece(message);
            } else {
                logger.error(String.format("处理失败，原始文件已备份至error目录,[%s]",filename));
                MessageUtils.errorRece(message);
            }
        } else {
            System.err.println("暂不处理,输入源不是文件");
            logger.error(String.format("暂不处理,输入源不是文件,[%s]",filename));
            MessageUtils.errorRece(message);
        }

    }
}

